unit ufrmDataModule;

interface

uses
  SysUtils, Classes, DBXpress, IBDatabase, IBDatabaseInfo, DB, SqlExpr;

type
  TMConn = class(TDataModule)
    dbConn: TSQLConnection;
    IBdbInfo: TIBDatabaseInfo;
    IBDb: TIBDatabase;
    procedure DataModuleCreate(Sender: TObject);
    function PodeAcessarBanco(PAccExcl: boolean): boolean;
    function PegaQtConexoes(): integer;
    procedure FechaArqAcessoBanco();
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  MConn: TMConn;
  VFsAccess: TFileStream;

implementation

{$R *.dfm}

// Abre o banco de dados
procedure TMConn.DataModuleCreate(Sender: TObject);
begin
  // Configura conexao com o banco de dados
  DBConn.DriverName := 'interbase';
  DBConn.LibraryName := 'dbexpint.dll';
  DBConn.VendorLib := 'gds32.dll'; //'fbembed.dll';
  DBConn.GetDriverFunc := 'getSQLDriverINTERBASE';
  //DBConn.Params.Values['Database'] := '192.168.1.1:C:\database\DB.FDB';
  DBConn.Params.Values['SQLDialect'] := '3';
  DBConn.Params.Values['Database'] := 'DB_FISIOTERAPIA.FDB';
  DBConn.Params.Values['User_Name'] := 'SYSDBA';
  DBConn.Params.Values['Password'] := 'masterkey';
  // Abre o banco de dados
  DBConn.Open;
end;

// Checa possibilidade de acesso ao banco - mode exclusivo ou nao
function TMConn.PodeAcessarBanco(PAccExcl: boolean): boolean;
begin
  // Tenta criar acesso exclusivo
  try
    if PAccExcl then
      VFsAccess := TFileStream.Create('AdmSys.acc', fmCreate or fmOpenReadWrite, fmShareExclusive)
    else
      VFsAccess := TFileStream.Create('AdmSys.acc', fmCreate or fmOpenReadWrite, fmShareDenyNone);
  except
    Result := false;
    exit;
  end;
  if PAccExcl then
    VFsAccess.Write('ACCEXC', Length('ACCEXC'))
  else
    VFsAccess.Write('ACCNOR', Length('ACCNOR'));
  Result := true;
end;

// Pega qtde usuarios conectados no banco de dados
function TMConn.PegaQtConexoes: integer;
begin
  IBDb.Open;
  result := IBDbInfo.UserNames.Count;
  IBDb.Close;
end;

// Fecha arquivo controle acesso banco
procedure TMConn.FechaArqAcessoBanco;
begin
  VFsAccess.Free;
end;

end.
